<template>
  <div class="product-card">
    <img :src="product.imgUrl" alt="商品图片" class="product-img">
    <div class="product-info">
      <h3 class="product-title">{{ product.title }}</h3>
      <p class="product-price">
        <span v-if="product.promoStatus === 2" class="promo-price">¥{{ product.promoPrice }}</span>
        <span v-else>¥{{ product.price }}</span>
      </p>
      <p class="product-stock">库存: {{ product.stock }}</p>
      <button @click="handleBuy" class="buy-btn">立即购买</button>
      <router-link :to="`/product/${product.id}`" class="detail-link">查看详情</router-link>
    </div>
  </div>
</template>

<script setup>
import { defineProps } from 'vue';
import { useRouter } from 'vue-router';
import { orderAPI } from '../services/api';

const props = defineProps({
  product: {
    type: Object,
    required: true
  }
});

const router = useRouter();

const handleBuy = async () => {
  try {
    await orderAPI.create(props.product.id, 1, props.product.promoId || null);
    alert('购买成功！');
  } catch (error) {
    alert('购买失败: ' + (error.message || '未知错误'));
  }
};
</script>

<style scoped>
.product-card {
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 16px;
  width: 250px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.product-img {
  width: 100%;
  height: 180px;
  object-fit: cover;
  border-radius: 4px;
}

.product-info {
  margin-top: 12px;
}

.product-title {
  font-size: 1.1rem;
  margin-bottom: 8px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.product-price {
  color: #e53935;
  font-weight: bold;
  margin-bottom: 8px;
}

.promo-price {
  color: #e53935;
  margin-right: 8px;
}

.product-stock {
  color: #666;
  font-size: 0.9rem;
  margin-bottom: 12px;
}

.buy-btn {
  background-color: #ff9800;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  margin-right: 8px;
}

.detail-link {
  color: #2196f3;
  text-decoration: none;
}

.detail-link:hover {
  text-decoration: underline;
}
</style>